﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.WorkFlow.Dtos.FlowLaunch;
using JNPF.Basics.Models.WorkFlow.Enums;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 流程发起
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-06-07 
    /// </summary>
    [Route("api/WorkFlow/[controller]")]
    public class FlowLaunchController : BaseApiController
    {
        private FlowTaskBll flowTaskBll = new FlowTaskBll();
        private FlowTaskNodeBll flowTaskNodeBll = new FlowTaskNodeBll();
        private FlowEngineBll flowEngineBll = new FlowEngineBll();
        private OrderBll orderBll = new OrderBll();
        private FlowTaskOperatorBll flowTaskOperatorBll = new FlowTaskOperatorBll();

        #region GET
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList([FromQuery] FlowLaunchListQuery input)
        {
            var pageInput = input.MapTo<PageInput>();
            pageInput.queryJson = JsonHelper.ToJson(new
            {
                input.startTime,
                input.endTime,
                input.flowCategory,
                input.flowId
            });
            var data = await flowTaskBll.GetLaunchList(pageInput);
            var outdata = data.list.MapToList<FlowLaunchListOutput>();
            var flowEngineList = await flowEngineBll.GetList();
            foreach (var item in outdata)
            {
                var entity = flowEngineList.Find(x => x.Id == item.flowId);
                if (entity != null)
                {
                    item.formData = entity.FlowTemplateJson.IsNotEmptyOrNull() ? entity.FlowTemplateJson : "";
                    item.formType = entity.FormType.IsNotEmptyOrNull() ? entity.FormType : 2;
                }

            }
            var output = new PageResult()
            {
                list = outdata,
                pagination = data.pagination
            };
            return Success(output);
        }
        #endregion

        #region POST
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            var entity = await flowTaskBll.GetInfo(id);
            if (entity != null)
            {
                await flowTaskBll.Delete(entity);
            }
            return Success("删除成功");
        }

        /// <summary>
        /// 撤回
        /// 注意：在撤回流程时要保证你的下一节点没有处理这条记录；如已处理则无法撤销流程。
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="input">流程经办</param>
        /// <returns></returns>
        [HttpPut("{id}/Actions/Withdraw")]
        public async Task<ResponseResult> Revoke(string id, [FromBody] FlowLaunchActionWithdrawInput input)
        {
            var flowTaskEntity = await flowTaskBll.GetInfo(id);
            var flowTaskNodeEntityList = await flowTaskNodeBll.GetList(flowTaskEntity.Id);
            var flowTaskNodeEntity = flowTaskNodeEntityList.Find(m => m.SortCode == 2);
            //if (flowTaskNodeEntity.Completion > 0)
            //{
            //    return Error("当前流程被处理，无法撤回流程");
            //}
            //else
            //{
                if (FlowModuleEnum.CRM_Order.Equals(flowTaskEntity.FlowCode))
                {
                    await orderBll.FlowRevoke(flowTaskEntity, input.handleOpinion);
                }
                else
                {
                    await flowTaskBll.Revoke(flowTaskEntity, input.handleOpinion);
                }
                return Success("撤回成功");
           // }
        }

        /// <summary>
        /// 催办
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("Press/{id}")]
        public async Task<ResponseResult> Press(string id)
        {
            var flowTaskEntity = await flowTaskBll.GetInfo(id);
            var stepId = flowTaskEntity.ThisStepId.Split(",");
            var flowTaskOperatorEntityList = (await flowTaskOperatorBll.GetList(id)).FindAll(x=>x.Completion==0);
            var processId = new List<string>();
            foreach (var item in stepId)
            {
                processId.Add(flowTaskOperatorEntityList.Find(x => x.NodeCode.Equals(item)).HandleId);
            }
            if (processId.Count>0)
            {
                Dictionary<string, object> message = new Dictionary<string, object>();
                message["type"] = FlowMessageEnum.wait;
                message["id"] = id;
                //审核提醒
                await flowTaskBll.MessagePush(flowTaskOperatorEntityList, flowTaskEntity.FullName + "【催办】", message.ToJson());
                return Success("催办成功");
            }
            return Error("未找到催办人");
        }

        #endregion
    }
}
